package nl.vu.few.ibivu.biomodels.client.ui.cytoscapeweb;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONValue;

public class CytoscapeWebDataField extends JavaScriptObject {
	protected CytoscapeWebDataField() {}
	
	public static CytoscapeWebDataField create(String name, CytoscapeWebDataFieldType type) {
		CytoscapeWebDataField instance = (CytoscapeWebDataField) JavaScriptObject.createObject();
		instance.setType(type);
		instance.setName(name);
		return instance;
	}
	
	public static CytoscapeWebDataField create(String name, CytoscapeWebDataFieldType type, JSONValue defValue) {
		CytoscapeWebDataField instance = create(name, type);
		if (defValue != null) {
			instance.setDefValue(defValue);
		}
		return instance;
	}
	
	public final native String getName() /*-{
		return this.name;
	}-*/;
	
	public final native CytoscapeWebDataFieldType getType() /*-{
		return @nl.vu.few.ibivu.biomodels.client.ui.cytoscapeweb.CytoscapeWebDataFieldType::valueOfLowerCase(Ljava/lang/String;)(this.type);
	}-*/;
	
	public final native JSONValue getDefValue() /*-{
		if (!this.defValue)
			return null;
			
		var value;
		switch(this.type) {
			case 'string':
				value = @com.google.gwt.json.client.JSONString::new(Ljava/lang/String;)(this.defValue);
				break;
			case 'boolean':
				value = @com.google.gwt.json.client.JSONBoolean::getInstance(Z)(this.defValue);
				break;
			case 'int':
			case 'number':
				value = @com.google.gwt.json.client.JSONNumber::new(D)(this.defValue);
				break;
			default:
				value = @com.google.gwt.json.client.JSONObject::new(Lcom/google/gwt/core/client/JavaScriptObject;)(this.defValue);
				break;
		}	
		return value;
	}-*/;

	public final native void setName(String name) /*-{
		this.name = name;
	}-*/;
	
	public final native void setType(CytoscapeWebDataFieldType type) /*-{
		this.type = type.toString().toLowerCase();
	}-*/;
	
	public final native void setDefValue(JSONValue defValue) /*-{
		if (!defValue)
			return;
		if (defValue.@com.google.gwt.json.client.JSONValue::isNull())
			return;
		switch(this.type) {
			case 'string':
				var value = defValue.@com.google.gwt.json.client.JSONValue::isString()();
				this.defValue = value.@com.google.gwt.json.client.JSONString::stringValue()();
				break;
			case 'boolean':
				var value = defValue.@com.google.gwt.json.client.JSONValue::isBoolean()();
				this.defValue = value.@com.google.gwt.json.client.JSONBoolean::booleanValue()();
				break;
			case 'int':
			case 'number':
				var value = defValue.@com.google.gwt.json.client.JSONValue::isNumber()();
				this.defValue = value.@com.google.gwt.json.client.JSONNumber::doubleValue()();
				break;
			default:
				var value = defValue.@com.google.gwt.json.client.JSONValue::isObject()();
				this.defValue = value.@com.google.gwt.json.client.JSONObject::getJavaScriptObject()();
				break;
		}	
	}-*/;
}
